package org.seckill.dao;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.seckill.entity.Seckill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by Administrator on 2017-8-15.
 * redis(key,value)  get  put
 */
public class RedisDao {

    private final RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);

    private final Logger logger = LoggerFactory.getLogger(RedisDao.class);

    private final  JedisPool jedisPool;

    public RedisDao(String ip,int port) {
        this.jedisPool = new JedisPool(ip,port);
    }

    public Seckill getSeckill(Long seckillId) {

        try {
            Jedis jedis = jedisPool.getResource();

            try {
                String key = "seckillId:" + seckillId;
                byte[] bytes = jedis.get(key.getBytes());
                if(bytes != null) {
                    Seckill seckill = schema.newMessage();
                    ProtobufIOUtil.mergeFrom(bytes, seckill, schema);
                    return seckill;
                }
            } finally {
                jedis.close();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return null;
    }


    public String putSeckill(Seckill seckill) {

        try {
            Jedis jedis = jedisPool.getResource();
            try {
                byte[] bytes = ProtobufIOUtil.toByteArray(seckill,
                        schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
                String key ="seckillId:" + seckill.getSeckillId();
                int timeout = 60*60;
                String result = jedis.setex(key.getBytes(),timeout,bytes);
                return result;
            } finally {
                jedis.close();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return null;

    }

}
